package com.zero;

import io.smallrye.mutiny.Multi;
import io.smallrye.mutiny.Uni;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.ApplicationScoped;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Observable;

/**
 * 天气服务类
 */
@ApplicationScoped
public class WeatherService {

    private static Logger LOG = LoggerFactory.getLogger(WeatherService.class);

    @ConfigProperty(name = "current.city")
    private String city;

    public Uni<String> printCity(){
        return Uni.createFrom().item("当前城市：" + city);
    }

    public Multi<String> getCityWeather(String city) throws IOException {
        String uri = "http://wthrcdn.etouch.cn/weather_mini?city=" + city;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = httpClient.execute(new HttpGet(uri));
        String result = EntityUtils.toString(response.getEntity(), Charset.forName("UTF-8"));
        LOG.info("The weather of {}: {}", city, result);
        return Multi.createFrom().item(result);
    }

    public Multi<String> getWeather() throws IOException {
        return getCityWeather(city);
    }

}
